package eu.dominicum.ft.pd;

import eu.dominicum.ft.pd.mao.MakeTeamMAO;
import eu.dominicum.ft.pd.mao.MakeTeamMemberMAO;

import java.util.ArrayList;
import java.util.List;

/**
 * A Team.
 *
 * @author Harry Klerks
 * @since 2013M1
 */
public class Team extends PersistentDomainObject {

    /**
     * The number 10.
     */
    private static final int TEN = 10;
    /**
     * This Team's sequence number.
     */
    private Integer sequence;
    /**
     * The Tour in which this Team participates(d).
     */
    private Tour tour;
    /**
     * A list of this Team's Team Members.
     */
    private final List<TeamMember> teamMembers = new ArrayList<>();

    /**
     * Protected constructor to satisfy JPA.
     */
    protected Team() {
    }

    /**
     * .
     *
     * @return Tour
     */
    public final Tour getTour() {
        return tour;
    }

    /**
     * .
     *
     * @return Integer.
     */
    public final Integer getSequence() {
        return sequence;
    }

    /**
     * .
     *
     * @return List<TeamMember>
     */
    public final List<TeamMember> getTeamMembers() {
        return teamMembers;
    }

    /**
     * Makes a Team object.
     *
     * @param makeTeamMAO -
     * @return Team
     */
    static Team make(final MakeTeamMAO makeTeamMAO) {

        Team newTeam = new Team();

        newTeam.sequence = makeTeamMAO.getSequence();
        newTeam.tour = makeTeamMAO.getTour();

        TeamMember newTeamMember;
        MakeTeamMemberMAO makeTeamMemberMAO;
        Integer yerseyNumberSuffixLowDigit = makeTeamMAO.getYerseyNumberLow();
        while (yerseyNumberSuffixLowDigit <= makeTeamMAO.getYerseyNumberHigh()) {
            makeTeamMemberMAO = new MakeTeamMemberMAO();
            makeTeamMemberMAO.setYerseyNumber(((makeTeamMAO.getSequence() - 1) * TEN) + yerseyNumberSuffixLowDigit++);
            makeTeamMemberMAO.setTeam(newTeam);
            newTeamMember = TeamMember.make(makeTeamMemberMAO);
            newTeam.addToTeamMembers(newTeamMember);
        }

        return newTeam;
    }

    /**
     * Adds the given {@link TeamMember} object to the list of associated {@link TeamMember} objects.
     *
     * @param teamMember -
     */
    final void addToTeamMembers(final TeamMember teamMember) {

        this.teamMembers.add(teamMember);
    }

    /**
     * Find a team member by the given yersey number.
     *
     * @param yerseyNumber -
     * @return TeamMember
     */
    public final TeamMember findTeamMemberByYerseyNumber(final Integer yerseyNumber) {

        for (TeamMember teamMember : this.teamMembers) {
            if (teamMember.getYerseyNumber().equals(yerseyNumber)) {
                return teamMember;
            }
        }

        return null;
    }
}
